package cn.kgc.shiro.shiro;

import cn.kgc.shiro.entity.Role;
import cn.kgc.shiro.entity.User;
import cn.kgc.shiro.entity.UserRole;
import cn.kgc.shiro.mapper.RoleMapper;
import cn.kgc.shiro.mapper.UserMapper;
import cn.kgc.shiro.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 课工场
 * @date 2024/3/26
 * @description
 */
@Slf4j
public class CustomerRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取主身份信息  用户名      SimpleAuthenticationInfo
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        log.info("--------------CustomerRealm doGetAuthorizationInfo---------------");
        log.info("primaryPrincipal={}",primaryPrincipal);
        //  TODO  根据用户名  查询用户角色信息
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getUsername,primaryPrincipal);
        User user = userMapper.selectOne(lambda);
        Integer uid = user.getId();

        LambdaQueryWrapper<UserRole> lambda1 = new QueryWrapper<UserRole>().lambda();
        lambda1.eq(UserRole::getUid,uid);
        List<Integer> rid = userRoleMapper.selectList(lambda1)
                        .stream().map(userRole -> userRole.getRid()).collect(Collectors.toList());

        LambdaQueryWrapper<Role> lambda2 = new QueryWrapper<Role>().lambda();
        lambda2.in(Role::getId,rid);

        List<String> roleNames = roleMapper.selectList(lambda2).stream()
                .map(role -> role.getRoleName()).collect(Collectors.toList());

        log.info("roleNames={}",roleNames);

        // 将用户的角色信息 封装  SimpleAuthorizationInfo
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleNames);

        // 将用户拥有的权限字符串封装
//        simpleAuthorizationInfo.addStringPermissions();

        return simpleAuthorizationInfo;
    }

    // 认证
    //  login中传递的参数  最终会被传递到doGetAuthenticationInfo 方法中
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("--------CustomerRealm doGetAuthenticationInfo------------------");

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();

        // 根据用户名  查询用户信息
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getUsername,username);
        User user = userMapper.selectOne(lambda);

        if (ObjectUtils.isNotNull(user)){  //  用户名正确
            SimpleAuthenticationInfo simpleAuthenticationInfo =
                    new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
            return simpleAuthenticationInfo;
        }

        return null;
    }
}
